/**
 * 图片旋转后返回base64
 * @param {Object} img 图片对象
 * @param {Number} rotate 旋转角度 90° 180° 270° 360°=default
 * @returns {String} base64图片
 *
 */
const imageRotate =(img, rotate) => {
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')
  switch (rotate) {
  case 90: // 旋转90°
    canvas.width = img.height
    canvas.height = img.width
    ctx.rotate((90 * Math.PI) / 180)
    ctx.drawImage(img, 0, -img.height, img.width, img.height)
    break
  case 180: // 旋转180°
    canvas.width = img.width
    canvas.height = img.height
    ctx.rotate((180 * Math.PI) / 180)
    ctx.drawImage(img, -img.width, -img.height, img.width, img.height)
    break
  case 270: // 旋转270°
    canvas.width = img.height
    canvas.height = img.width
    ctx.rotate((-90 * Math.PI) / 180)
    ctx.drawImage(img, -img.width, 0, img.width, img.height)
    break
  default:
    canvas.width = img.width
    canvas.height = img.height
    ctx.drawImage(img, 0, 0, img.width, img.height)
    break
  }
  return canvas.toDataURL('image/png')
}

/**
 * 将base64编码转回file文件
 * @param {*} dataurl 
 * @param {*} filename 
 * @returns 
 */
const dataURLtoFile= async (dataurl, filename) =>{
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let  n = bstr.length
  let u8arr = new Uint8Array(n)
  while(n--){
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {type:mime})
}

/**
 * @description: 图片压缩
 */
const compressImg=(file, width, height) =>{
  let disposeFile = file
  if (Object.prototype.toString.call(file) === '[object Blob]') {
    disposeFile = new File([file], file.name, { type: file.type })
  }

  // 大小小于0.5Mb之后进行压缩
  const fileSize = parseFloat(parseInt(disposeFile['size']) / 1024 / 1024 / 2).toFixed(2)
  // 小于0.5m不压缩
  if (fileSize < 0.5) return file
  const read = new FileReader()
  read.readAsDataURL(disposeFile)
  return new Promise((resolve, reject) => {
    try {
      read.onload = (e) => {
        const img = new Image()
        img.src = e.target.result
        img.onload = function () {
          let w = Math.floor(width / 2),
            h = Math.floor(height / 2)
          //生成canvas
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          let base64
          canvas.setAttribute('width', w)
          canvas.setAttribute('height', h)
          ctx.drawImage(this, 0, 0, w, h)
          // 按大小压缩
          if (fileSize <= 1) {
            // 如果图片小于一兆 那么不执行压缩操作
            base64 = canvas.toDataURL(disposeFile['type'], 0.8)
          } else if (fileSize > 1 && fileSize < 2) {
            // 如果图片大于1M并且小于2M 那么压缩0.5
            base64 = canvas.toDataURL(disposeFile['type'], 0.5)
          } else {
            // 如果图片超过2m 那么压缩0.2
            base64 = canvas.toDataURL(disposeFile['type'], 0.3)
          }
          resolve(dataURLtoFile(base64, disposeFile.name))
        }
      }
    } catch (error) {
      reject(disposeFile)
    }
  })
}

/**
 * 
 * @param {*} file 
 * @returns 
 */
const transformFile =(file) =>{
  const height = 640 //图片的高
  const width = 360 //图片的宽
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = height
      canvas.height = width
      const img = document.createElement('img')
      img.src = reader.result
      img.onload = async () => {
        //console.log(this.clientWidth)
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, height, width)
        let base64 = canvas.toDataURL(file['type'], 0.8)
        let files = await dataURLtoFile(base64, file.name)
        resolve(files)
        // canvas.toBlob(resolve, 'image/jpeg', 1)
      }
    }
  })
}

export default {
  dataURLtoFile, compressImg, transformFile, imageRotate
}